﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using OpenTK;
using OpenTK.Input;
using OpenTK.Graphics;


#if EMBEDDED
    using OpenTK.Graphics.ES20;
#else
using OpenTK.Graphics.OpenGL;
#endif

namespace MonoSettlers.RenderSystem
{
    /// <summary>
    /// Provides convenient access to GLSL shaders. As with other OpenGL related 
    /// unmanaged resources, you MUST dispose any allocated instance explicitly,
    /// otherwise you will get an exception by the time such an leaking object is GCed.
    /// Also see <see cref="GLProgram"/>.
    /// </summary>
    internal class GLShader : IDisposable
    {
        private int? m_ShaderID;

        /// <summary>
        /// Vertex- or pixelshader?
        /// </summary>
        public ShaderType Type { get; private set; }
        /// <summary>
        /// Source code for the shader.
        /// </summary>
        public String Source { get; private set; }
        /// <summary>
        /// OpenGL specific shader ID.
        /// </summary>
        public int ShaderID { get { return m_ShaderID.Value; } }

        /// <summary>
        /// A resource leak check. Due to wrong thread context, we usually can't release OpenGL resources
        /// in class destructors!
        /// </summary>
        ~GLShader()
        {
            if (m_ShaderID.HasValue)
                Log.LogExceptionCritical(new ArgumentException("Shader has not been released before GC."));
        }

        /// <summary>
        /// Releases all unmanaged resources associated with this shader.
        /// </summary>
        public void Dispose()
        {
            if (!m_ShaderID.HasValue)
                return;

            GL.DeleteShader(ShaderID); GLRenderer.CheckError();

            m_ShaderID = null;
        }

        /// <summary>
        /// Loads a new shader from file. For performance reasons, shaders might be
        /// cached later on, but this won't have an impact on this API.
        /// </summary>
        /// <param name="inFileName">A file containing the shader source code.</param>
        public GLShader(String inFileName)
        {
            try
            {
                if (inFileName.EndsWith(".vert"))
                    Type = ShaderType.VertexShader;
                else if (inFileName.EndsWith(".frag"))
                    Type = ShaderType.FragmentShader;
                else
                    throw new ArgumentException();

                Source = File.ReadAllText(inFileName);

                String log;

                try
                {
                    m_ShaderID = GL.CreateShader(Type); GLRenderer.CheckError();
                    GL.ShaderSource(ShaderID, Source); GLRenderer.CheckError();
                    GL.CompileShader(ShaderID); GLRenderer.CheckError();

                    log = GL.GetShaderInfoLog(ShaderID);
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Shader \"" + inFileName + "\" failed to load.", e);
                }

                if (!log.StartsWith("No errors."))
                    throw new ArgumentException("Shader \"" + inFileName + "\" failed to compile: \"" + log + "\".");
            }
            catch (Exception e)
            {
                Dispose();

                throw e;
            }
        }
    }
}
